package com.blockmeta.bbs.businesslibrary.net.manager;

import android.content.Context;
import android.widget.ImageView;

import com.blockmeta.bbs.baselibrary.net.callback.Callback;
import com.blockmeta.bbs.baselibrary.utils.ToastUtil;
import com.blockmeta.bbs.businesslibrary.R;
import com.blockmeta.bbs.businesslibrary.constant.NetConstant;
import com.blockmeta.bbs.businesslibrary.net.okhttp.OkHttpPostString;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

/**
 * Created by author on 2018/3/26.
 */

public class UserFavManager {
    public static boolean isLogin;
    public static String favid;


    /**
     * @param tag      check 检查  "" 添加  delete 删除
     * @param id       帖子Id
     * @param fav_id
     * @param mContext
     */
    public static void getUserFav(final String tag, String id, final String fav_id, Context mContext, final ImageView img, final CallBackFavid callback) {
        if (!AccountHelper.isLogin()) {
            return;
        }
        favid = fav_id;
        final HashMap<String, String> map = new HashMap<>();
        map.put("op", tag);
        map.put("id", id);
        if (tag.equals("delete")) {
            map.put("favid", fav_id);
        }
        OkHttpPostString.postString(mContext, NetConstant.ADD_BBS_FAV, map, "uid", AccountHelper.getUid(), new Callback() {
            @Override
            public void onError(String resp) {
//                ToastUtil.show(resp.toString());
            }

            @Override
            public void onResponse(String resp, int id) {
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(resp);
                    favid = jsonObject.getString("favid");
                } catch (JSONException e) {
                    setFavIcon(img, false);
                }
                if (tag.equals("delete")) { //删除
                    setFavIcon(img, false);
                } else if (tag.equals("check")) {//检查有没有
                    if (favid.equals("0")) {
                        setFavIcon(img, false);
                    } else {
                        setFavIcon(img, true);
                    }
                } else {
                    //添加
                    setFavIcon(img, true);
                }
                callback.callBackFavid(favid);
            }
        });

    }

    /**
     * @param favImg 图标
     * @param favTag 图标状态
     */
    public static void setFavIcon(ImageView favImg, boolean favTag) {
        favImg.setImageResource(favTag ? R.drawable.fav_actived : R.drawable.fav_b);
    }

    public interface CallBackFavid {
        void callBackFavid(String newFavID);
    }

}
